package utils

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

// SetupLogrus 设置日志配置，支持按大小切割
// maxSize: 单个日志文件最大大小(MB)
// maxBackups: 保留的旧日志文件数量
// maxAge: 保留旧日志文件的最大天数
func SetupLogrus(path string, maxSize, maxBackups, maxAge int) (*logrus.Logger, func(), error) {
	// 确保日志目录存在
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return nil, nil, fmt.Errorf("create log dir failed: %w", err)
	}

	// 配置日志切割
	logWriter := &lumberjack.Logger{
		Filename:   path,
		MaxSize:    maxSize,    // MB
		MaxBackups: maxBackups, // 保留旧日志数量
		MaxAge:     maxAge,     // 保留天数
		LocalTime:  true,
	}

	logger := logrus.New()
	logger.SetOutput(io.MultiWriter(logWriter, os.Stdout)) // 同时输出到文件和终端(如果需要的话)
	logger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	logger.SetReportCaller(true)
	logger.SetLevel(logrus.DebugLevel)

	// 返回清理函数
	cleanup := func() {
		logWriter.Close()
	}

	return logger, cleanup, nil
}
